<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use think\Db;
use think\Request;
use think\Validate;

class Activity extends Common {
    /**
     * @param $value
     * @return mixed
     */
    public function index() {
        $where['delete_time'] = 0;

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id', 'id'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['update_time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['update_time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['update_time'] = ['elt', strtotime($end)];
        }

        $state = input('state');
        if ($state || $state === '0') {
            $this->assign('state', $state);
            $where['state'] = $state;
        }
        $status = input('status');
        if ($status || $status === '0') {
            $this->assign('status', $status);
            $where['status'] = $status;
        }

        $data = Db::name('activity_offline')
            ->where($where)
            ->field('*')
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['user']     = _user_cache($item['user_id']);
                $item['category'] = Db::name('activity_category')->where(['id' => $item['category']])->cache(60)->value('title');
                $item['images']   = explode(',', $item['images']);
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

    /**
     * @param $id
     * @param $shenhe
     * @param $reason
     */
    public function shenhe($id, $shenhe, $reason = '') {
        $time                = time();
        $activity            = Db::name('activity_offline')->where(['id' => $id])->find();
        $result              = Db::name('activity_offline')->where(['id' => $id])->update(['status' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
        $activity['content'] = _substr($activity['content']);
        if ($result) {
            if ($activity['user_id']) {
                switch ((int) $shenhe) {
                case -1:
                    Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再认领", '');
                    Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>2]);
                    break;
                case 0:
                    Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】重新审核中", '');
                    Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>2]);
                    break;
                case 1:
                    Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】审核通过", '');
                    Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>1]);
                    break;
                }
            }
            return ['ret' => '操作成功'];
        } else {
            return ['err' => '操作失败'];
        }
    }

    /**
     * @return mixed
     */
    public function shenheall() {
        if (request()->isAjax()) {
            $post   = input('post.');
            $shenhe = input('type');
            $reason = '';
            $time   = time();
            if (input('?post.delAll')) {
                $post    = $post['delAll'];
                $userids = [];
                foreach ($post as $k => $id) {
                    $activity            = Db::name('activity_offline')->where(['id' => $id])->find();
                    $activity['content'] = _substr($activity['content']);
                    $userids[]           = $activity['user_id'];
                    if ($shenhe == 'del') {
                    } else {
                        if (!$activity['user_id']) {
                            continue;
                        }
                        switch ((int) $shenhe) {
                        case -1:
                            Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】被驳回" . ($reason ? "，驳回原因：" . $reason : "") . "，请重新编辑后再认领", '');
                            Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>2]);
                            break;
                        case 0:
                            Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】重新审核中", '');
                            Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>2]);
                            break;
                        case 1:
                            Privatechat::notice($activity['user_id'], "您发布的实地活动【" . $activity['content'] . "】审核通过", '');
                            Db::name('dymanic')->where(['source_type'=>4,'source_id'=>$id])->update(['shenhe'=>1]);
                            break;
                        }
                    }
                }

                if ($shenhe == 'del') {
                    Db::name('activity_offline')->where(['id' => ['in', $post]])->delete();
                } else {
                    $result = Db::name('activity_offline')->where(['id' => ['in', $post]])->update(['status' => $shenhe, 'reason' => $reason, 'update_time' => $time]);
                }

                $data = ['ret' => '操作成功'];
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }

    /**
     * @return mixed
     */
    public function category() {
        $category = Db::name('activity_category')->order('sort desc,id asc')->select();
        $this->assign('data', $category);
        return $this->fetch();
    }

    /**
     * @return mixed
     */
    public function categoryAdd() {
        $id = input("id");

        if (request()->isAjax()) {
            $post = input('post.');

            //开始验证
            $validate = new Validate([
                ['title', 'require|max:20', '名称不能为空|长度不能超过20字符'],
            ]);

            $data = [
                'title' => $post['title'],
            ];

            if ($validate->check($data)) {
                $time                = time();
                $post['update_time'] = $time;
                if (!$id) {
                    //添加数据
                    $typename = db('activity_category')->where(['title' => $post['title']])->find();
                    if ($typename) {
                        return ['err' => '名称已存在'];
                    }
                    $post['create_time'] = $time;

                    $res = db('activity_category')->insert($post);
                    if ($res) {
                        $data = ['ret' => '添加成功'];
                    } else {
                        $data = ['err' => '添加失败'];
                    }
                } else {
					//修改数据
                    $res = db('activity_category')->where('id', $id)->update($post);
                    if ($res) {
                        $data = ['ret' => '修改成功'];
                    } else {
                        $data = ['err' => '修改失败'];
                    }
                }
            } else {
                $data = ["err" => $validate->getError()];
            }
        } else {
            if ($id) {
                $name = db('activity_category')->where('id', $id)->find();

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    $data = ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }

        return $data;
    }

    /**
     * @return mixed
     */
    public function CategoryDele() {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = db('activity_category')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function joins() {
        $where = ['a.paystate' => 1];

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id', 'active_id'])) {
                $where['a.'.$search_type] = $search_name;
            } else {
                $where['b.'.$search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['create_time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['create_time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['create_time'] = ['elt', strtotime($end)];
        }

        $state = input('state');
        if ($state || $state === '0') {
            $this->assign('state', $state);
            $where['a.state'] = $state;
        }

        $data = Db::name('activity_join')
        	->alias('a')
        	->join('activity_offline b', 'a.active_id=b.id')
            ->where($where)
            ->field('a.*,b.content')
            ->order('a.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function ($item) {
                $item['user']     = _user_cache($item['user_id']);
                return $item;
            });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }
    public function add()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');
            $db = Db::name('activity_offline')->where('id', $id)->update($post);
            if ($db !== false) {
                $data = ['ret' => '修改成功'];
            } else {
                $data = ['err' => '修改失败'];
            }
        } else {
            if ($id) {
                $name = Db::name('activity_offline')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }


    public function list() {
        $where['delete_time'] = 0;

        $search_name = input('param.name');
        $search_type = input('param.search');
        $this->assign('name', $search_name);
        $this->assign('search', $search_type);
        if ($search_name && $search_type) {
            if (in_array($search_type, ['user_id', 'id'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', "%$search_name%"];
            }
        }

        $start = input('start');
        $end   = input('end');
        $this->assign('start', $start);
        $this->assign('end', $end);
        if ($start && $end) {
            $where['update_time'] = ['between', [strtotime($start), strtotime($end)]];
        } elseif ($start && !$end) {
            $where['update_time'] = ['egt', strtotime($start)];
        } elseif (!$start && $end) {
            $where['update_time'] = ['elt', strtotime($end)];
        }

        $is_hidden = input('is_hidden');
        if ($is_hidden || $is_hidden === '0') {
            $this->assign('is_hidden', $is_hidden);
            $where['is_hidden'] = $is_hidden;
        }
        $state = input('state');
        if ($state || $state === '0') {
            if ($state == 0) {
                $where['start_time'] = ['>', time()];
            } else if ($state == 1) {
                $where['start_time'] = ['<=', time()];
                $where['end_time'] = ['>', time()];
            } else if ($state == 2) {
                $where['end_time'] = ['<', time()];
            }
            $this->assign('state', $state);
        }

        $data = Db::name('activity_list')
            ->where($where)
            ->field('*')
            ->order('sort desc, id asc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }
    public function addList()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');
            $post['content'] = Request::instance()->post('content','','htmlspecialchars');
            $post['start_time'] = strtotime($post['start_time']);
            $post['end_time'] = strtotime($post['end_time']);
            if ($post['start_time'] >= $post['end_time']) return ['err'=>'时间异常'];
            if ($id) {
                $post['update_time'] = time();
                $db = Db::name('activity_list')->where('id', $id)->update($post);
                $method = '修改';
            } else {
                $post['create_time'] = time();
                $db = Db::name('activity_list')->insert($post);
                $method = '创建';
            }
            if ($db !== false) {
                $data = ['ret' => $method.'成功'];
            } else {
                $data = ['err' => $method.'失败'];
            }
        } else {
            if ($id) {
                $name = Db::name('activity_list')->find($id);

                if ($name) {
                    $name['start_time'] = date('Y-m-d H:i:s',$name['start_time']);
                    $name['end_time'] = date('Y-m-d H:i:s',$name['end_time']);
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }
    public function delList() {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = db('activity_list')->where('id',$id)->update(['delete_time'=>time()]);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

}